package com.secneo.appshare.activities;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

import com.secneo.appshare.AppShareApplication;
import com.secneo.appshare.R;
import com.secneo.appshare.adapter.FeedsAdapter;
import com.secneo.appshare.adapter.FeedsSinaFansAdapter;
import com.secneo.appshare.api.LocalStore;
import com.secneo.appshare.api.RemoteApi.Feed;
import com.secneo.appshare.api.RemoteApi.Feeds;
import com.secneo.appshare.api.impl.RemoteApiImpl;
import com.secneo.appshare.common.Constants;
import com.secneo.appshare.threads.FeedsThread;
//我的粉丝
public class MyZoneFansActivity extends CommonMenuActivity implements OnClickListener
{
	
	enum MyZoneFansPage{
		MyFansPage,
		InviteSinaFansPage
	}
	
	private int mPageNumber;
	private int mFocusPosition;
	private boolean mReadyToGetFeeds = false;
	private ProgressDialog mDynDisPMProgressBar = null;
	private Feeds mLocalFeeds = new Feeds();
	
	
	private LinearLayout mZoneMyFansLayout;
	private TextView mMyFansTxt;
	private GridView mMyFansGridView;

	private LinearLayout mZoneInviteSinaFansLayout;
	private TextView mInviteSinaFansTxt;
	private Button mBtnInviteAll;
	private ListView mInviteSinaFansListView;
	
	private LinearLayout mZoneLoginSinaLayout;
	private Button mBtnSinaLogin;
	private Button mBtnSinaRegister;
	
	private RadioButton buttonMyFans;
	private RadioButton buttonInviteSinaFans;
	
	private Button mRetIv;
	
	private MyZoneFansPage currentControl ;
	
	private LinearLayout progress_layout;
	private View errorView;
	
	private FeedsThread zoneFansThread = null;
	
	private FeedsAdapter feedAdapter = null;
	private FeedsSinaFansAdapter sinaFansAdapter = null;
	
	
	public static final int MSG_GET_OTHER_USER_ICON = 101;
	Drawable dw =null;
    public int radioChecked=-1; 
    
    public Handler mHandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
				case Constants.MSG_GET_FEEDS_NETWORK_ERROR:
					mReadyToGetFeeds = true;
					if(mDynDisPMProgressBar != null && mDynDisPMProgressBar.isShowing()){
						mDynDisPMProgressBar.dismiss() ;
					}
					showNetworkErrView(Constants.MSG_GET_FEEDS_NETWORK_ERROR) ;
					break;
					
				case Constants.MSG_GET_MY_FANS_FINISH:
					mReadyToGetFeeds = true;
					if(mDynDisPMProgressBar != null && mDynDisPMProgressBar.isShowing()){
						mDynDisPMProgressBar.dismiss() ;
					}
					
					updateFeeds(zoneFansThread.getFeeds());
					
					progress_layout.setVisibility(View.GONE);
					refreshMyFansGridView(mLocalFeeds);
					break;
					
				case Constants.MSG_GET_SINA_FANS_FINISH:
					progress_layout.setVisibility(View.GONE);
					refreshInviteSinaFansListView(zoneFansThread.getFeeds());
					break;
					
				case Constants.MSG_GET_FEEDICON_FINISH:
					if(buttonMyFans.isChecked())
					{
						mMyFansGridView.invalidateViews();
						return;
					}
					else if(buttonInviteSinaFans.isChecked())
					{
						mInviteSinaFansListView.invalidateViews();
						return;
					}
					break;
					
				default:
					break ;
			}
			super.handleMessage(msg);
		}

	};

	
	private void clearFeeds(){
		mPageNumber = 1;
		mFocusPosition = 0;
		
		if(null!=mLocalFeeds.feeds){
			mLocalFeeds.feeds.clear();
		}
	}


	private void updateFeeds(Feeds feeds){
		++mPageNumber;
		if(null==mLocalFeeds.feeds){
			mLocalFeeds.feeds = new ArrayList<Feed>();
		}
		mLocalFeeds.feeds.addAll(feeds.feeds);
		mLocalFeeds.fb_invite_popup = feeds.fb_invite_popup;
		mLocalFeeds.msgs = feeds.msgs;
		mLocalFeeds.total = feeds.total;
		mLocalFeeds.fansTotal = feeds.fansTotal;
		mLocalFeeds.attentTotal = feeds.attentTotal;
	}
	

	private void showNetworkErrView(int action){
		errorView.setVisibility(View.VISIBLE);
		progress_layout.setVisibility(View.GONE);
		mZoneLoginSinaLayout.setVisibility(View.GONE);
		enableToggleButtons(true);
	}
	
	public void refreshMyFansGridView(final Feeds feeds) 
	{
		feedAdapter = new FeedsAdapter(this, feeds.feeds);
		feedAdapter.setNewIconVisible(true);
		mZoneMyFansLayout.setVisibility(View.VISIBLE);

		int totalFans = feeds.total;
		String title = MyZoneFansActivity.this.getResources().getString(R.string.title_my_fans, totalFans);
		mMyFansTxt.setText(title);
		
		mMyFansGridView.setNumColumns(4);
		mMyFansGridView.setAdapter(feedAdapter);
		mMyFansGridView.setSelection(mFocusPosition);
		mMyFansGridView.setOnItemClickListener(new OnItemClickListener()
		{
			public void onItemClick(AdapterView parent, View v, int position, long id)
			{
				try 
				{
					Feed userInfo = feeds.feeds.get(position);
					Intent intent = new Intent(); 
					intent.setClass(MyZoneFansActivity.this, AppsOtherUserActivity.class);

					Bundle mBundle = new Bundle();
					String uid = LocalStore.getLocaleStoreInstance(MyZoneFansActivity.this).getUid();
					mBundle.putString("uid", uid);
					mBundle.putString("other_uid", userInfo.uid);
					mBundle.putString("user_icon", userInfo.user_icon);
					mBundle.putString("user_name", userInfo.user_name);
					intent.putExtras(mBundle);
					startActivity(intent);
					
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		});
		
		enableToggleButtons(true);
	}
	

	public void refreshInviteSinaFansListView(final Feeds feeds) 
	{
		sinaFansAdapter = new FeedsSinaFansAdapter(this, feeds.feeds);
		mZoneInviteSinaFansLayout.setVisibility(View.VISIBLE);

		String title = MyZoneFansActivity.this.getResources().getString(R.string.title_invite_sina_fans);
		mInviteSinaFansTxt.setText(title);
		
		mInviteSinaFansListView.setAdapter(sinaFansAdapter);
		mInviteSinaFansListView.setOnItemClickListener(new OnItemClickListener()
		{
			public void onItemClick(AdapterView parent, View v, int position, long id)
			{
				try 
				{
					Feed userInfo = feeds.feeds.get(position);
					Intent intent = new Intent(); 
					intent.setClass(MyZoneFansActivity.this, AppsOtherUserActivity.class);

					Bundle mBundle = new Bundle();
					String uid = LocalStore.getLocaleStoreInstance(MyZoneFansActivity.this).getUid();
					mBundle.putString("uid", uid);
					mBundle.putString("other_uid", userInfo.uid);
					mBundle.putString("user_icon", userInfo.user_icon);
					mBundle.putString("user_name", userInfo.user_name);
					intent.putExtras(mBundle);
					startActivity(intent);
					
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		});
		
		enableToggleButtons(true);
	}
	

	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.appshare_zone_fans);
		AppShareApplication.getInstance().addActivity(this);

		LocalStore.getLocaleStoreInstance(MyZoneFansActivity.this).setFollowerCounts(0) ;
		
		mPageNumber = 1;

		mZoneMyFansLayout = (LinearLayout) findViewById(R.id.zone_fans_layout);
		mMyFansTxt = (TextView) findViewById(R.id.my_fans_txt);
		mMyFansGridView = (GridView) findViewById(R.id.gridview_fans_feeds);
		mMyFansGridView.setOnScrollListener(mGridViewScrollListner) ;

		mZoneInviteSinaFansLayout = (LinearLayout) findViewById(R.id.zone_invite_sina_layout);
		mInviteSinaFansTxt = (TextView) findViewById(R.id.invite_sina_txt);
		mBtnInviteAll = (Button) findViewById(R.id.btnInviteAll);
		mInviteSinaFansListView = (ListView) findViewById(R.id.listview_invite_sina);

		mZoneLoginSinaLayout = (LinearLayout) findViewById(R.id.zone_login_sina);
		mBtnSinaLogin = (Button) findViewById(R.id.btnSinaLogin);
		mBtnSinaRegister = (Button) findViewById(R.id.btnSinaRegister);
		
		mBtnSinaLogin.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent= new Intent();
				intent.setClass(MyZoneFansActivity.this, LoginWeiboMethodActivity.class);
				Bundle bundle=new Bundle();
				bundle.putInt(Constants.EXIT_BEHAVIOUR,Constants.EXIT_BEHAVIOUR_GOTO_ZONE);
				intent.putExtras(bundle);
				startActivity(intent);
				finish();
			}
		});
		mBtnSinaRegister.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				smsRegister();
			}
		});
		

		mBtnInviteAll.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				int size = zoneFansThread.getFeeds().feeds.size();
				List<String> idList = new ArrayList<String>();
				for(int i=0; i<size; i++){
					if(zoneFansThread.getFeeds().feeds.get(i).box_checked){
						String name = zoneFansThread.getFeeds().feeds.get(i).user_name;
						Log.e("MyTag", "Selected:"+name);
						idList.add(zoneFansThread.getFeeds().feeds.get(i).uid);
					}
				}
				Log.e("MyTag", "Number:"+idList.size());
				/*
				RemoteApiImpl remoteApi = new RemoteApiImpl();
				String userId = LocalStore.getLocaleStoreInstance().getUid();
				String emailString = remoteApi.getEmail(mContext, userId);
				*/
			}
		});
		
		
		progress_layout = (LinearLayout) findViewById(R.id.progress_layout);
		errorView = MyZoneFansActivity.this.findViewById(R.id.error_user);
		
		buttonMyFans = (RadioButton) findViewById(R.id.button_my_fans);
		buttonMyFans.setOnClickListener(this);
		buttonMyFans.setChecked(true);
		buttonInviteSinaFans = (RadioButton) findViewById(R.id.button_invite_sina_fans);
		buttonInviteSinaFans.setOnClickListener(this);
		
		mRetIv = (Button)findViewById(R.id.img_ret) ;
		mRetIv.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				finish();
			}
		}) ;
		
		currentControl = MyZoneFansPage.MyFansPage ;
		
	}

	
	
	
	@Override
	public void onClick(View v)
	{
		if (v instanceof RadioButton) 
		{
			mMyFansGridView.setAdapter(null);
			if(feedAdapter != null)
			{
				feedAdapter.freeDrawable();
				feedAdapter=null;
			}
			
			errorView.setVisibility(View.GONE);
			
			enableToggleButtons(false);
			if(buttonMyFans.isChecked())
			{
				startGetMyFans();
				return;
			}
			else if(buttonInviteSinaFans.isChecked())
			{
				if(LocalStore.getLocaleStoreInstance().accountIsActive(Constants.ACCOUNT_LOGIN_ARRAY_INDEX_SINA)){
					startGetSinaFans();
				}
				else{
					showSinaLoginPromptView();
				}
				return;
			}
		}
	}
	
	// 获得我的粉丝列表
	private void startGetMyFans()
	{
		hideCurrentPage();
		
		currentControl = MyZoneFansPage.MyFansPage;
		progress_layout.setVisibility(View.VISIBLE);
		enableToggleButtons(false);
		
		String uid = LocalStore.getLocaleStoreInstance(this).getUid();

		zoneFansThread = new FeedsThread(this, mHandler, mPageNumber, uid, Constants.USER_TYPE_MY_FANS, Constants.feedGetTypeAll);
		zoneFansThread.start();
	}
	
	// 获得新浪好友列表
	private void startGetSinaFans()
	{
		hideCurrentPage();
		
		currentControl = MyZoneFansPage.InviteSinaFansPage;
		progress_layout.setVisibility(View.VISIBLE);
		enableToggleButtons(false);
		
		String uid = LocalStore.getLocaleStoreInstance(this).getUid();
		int n = 36;
		zoneFansThread = new FeedsThread(this, mHandler, n, uid, Constants.USER_TYPE_SINA_FANS, Constants.feedGetTypeAll);
		zoneFansThread.start();
	}
	
	// 获得新浪好友列表
	private void showSinaLoginPromptView()
	{
		hideCurrentPage();
		
		currentControl = MyZoneFansPage.InviteSinaFansPage;
		mZoneLoginSinaLayout.setVisibility(View.VISIBLE);
		enableToggleButtons(true);
	}


	
	
	private void hideCurrentPage(){
		progress_layout.setVisibility(View.GONE);
		mZoneMyFansLayout.setVisibility(View.GONE);
		mZoneInviteSinaFansLayout.setVisibility(View.GONE);
		mZoneLoginSinaLayout.setVisibility(View.GONE);
		errorView.setVisibility(View.GONE);
	}

	
	private void enableToggleButtons(boolean enable)
	{
		buttonMyFans.setClickable(enable);
		buttonInviteSinaFans.setClickable(enable);
	}


	@Override
	protected void onStart() 
	{
		if(buttonInviteSinaFans.isChecked())
		{
			if(LocalStore.getLocaleStoreInstance().accountIsActive(Constants.ACCOUNT_LOGIN_ARRAY_INDEX_SINA)){
				startGetSinaFans();
			}
			else{
				showSinaLoginPromptView();
			}
		}
		else if(buttonMyFans.isChecked())
		{
			startGetMyFans();
		}
		super.onRestart();
	}

	
	
	@Override
	protected void onDestroy() 
	{
		zoneFansThread.stopRun();
		mMyFansGridView.setAdapter(null);
		if(feedAdapter != null)
		{
			feedAdapter.freeDrawable();
			feedAdapter=null;
		}
		if(sinaFansAdapter != null)
		{
			sinaFansAdapter.freeDrawable();
			sinaFansAdapter=null;
		}

		if(mDynDisPMProgressBar != null && mDynDisPMProgressBar.isShowing()){
			mDynDisPMProgressBar.dismiss() ;
		}
		
		clearFeeds();

		super.onDestroy();
	}

	public void smsRegister()
	{
		RemoteApiImpl rai = new RemoteApiImpl() ;
		String registerNumber = rai.getSinaRegisterNumber(MyZoneFansActivity.this);
		
		if(null==registerNumber || "".equals(registerNumber)){
			Log.e("MyTag", "Sim: error in getting SimCard");
			return;
		}
		
		Uri uri = Uri.parse("smsto:"+registerNumber);
	      Intent intent = new Intent(Intent.ACTION_SENDTO,uri);
	      intent.putExtra("sms_body", "我正在使用安卓分享手机客户端玩新浪微博，方便又简单！");
	      startActivity(intent); 

	}
	

	private OnScrollListener mGridViewScrollListner = new OnScrollListener()
	{
		private int firstItem = 0;
		private int lastItem = 0;
		@Override
		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
		{
			firstItem = firstVisibleItem;
			lastItem = firstVisibleItem + visibleItemCount;
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState)
		{
			if (feedAdapter != null && lastItem == feedAdapter.getCount() && scrollState == OnScrollListener.SCROLL_STATE_IDLE)
			{
				Log.e("MyTag", "Total:"+mLocalFeeds.total);
				Log.e("MyTag", "return Size:"+mLocalFeeds.feeds.size());
				
				if(mLocalFeeds.total==mLocalFeeds.feeds.size()){
					return;
				}
				if (!mReadyToGetFeeds)
					return;
				mReadyToGetFeeds = false;
				
            	mDynDisPMProgressBar = ProgressDialog.show(
            			MyZoneFansActivity.this, null, "加载中，请稍候..." ,true);
				
				mFocusPosition = firstItem;
				
				String uid = LocalStore.getLocaleStoreInstance().getUid();

				zoneFansThread = new FeedsThread(MyZoneFansActivity.this, mHandler, mPageNumber, uid, 
						Constants.USER_TYPE_MY_FANS, Constants.feedGetTypeAll);
						
				zoneFansThread.start();
				
			}
		}
	};
	
	
}
